﻿Option Infer On
Imports CoreFX.API
Imports System
Imports System.IO
Imports System.Net
Imports System.Windows
Imports System.Windows.Controls
Imports System.Windows.Data
Imports System.Windows.Media
Imports System.Windows.Media.Animation
Imports System.Windows.Navigation
Imports Microsoft.VisualBasic
Imports Microsoft.VisualBasic.FileSystem
Imports CoreFX, ChatEngine, CoreFX.Interfaces, ChatEngine.Client, ChatEngine.Connections, CoreFX.Logging, ChatEngine.Client.Channel
Partial Public Class Window1
    Implements IChannelWindow
    Dim CName, Topic, PrevText, ChanName, Text, a, MessageText As String
    Event Disconnected()
    Shared WithEvents CEIVar As ChatEngine.Client.IRCClient
    Delegate Sub Nav()
    Delegate Sub ClearUserList(ByVal ChannelName As String)
    Delegate Sub DisplayMessage(ByVal E As ShowMessageArgs)
    Delegate Sub LoadUserList(ByVal E As Connections.NickListRecvArgs)
    Delegate Sub AddNewUser(ByVal User As String, ByVal ChannelName As String)
    Delegate Sub BroadcastMessage(ByVal User As String, ByVal Message As String)
    Delegate Sub SetUserModePic(ByVal E As Connections.UserModeArgs)
    Delegate Sub SetContentOfTab(ByVal Header As String, ByVal IsConsoleTab As Boolean)
    Delegate Sub ChangeNickDelegate(ByVal Prev As String, ByVal New1 As String)
    Delegate Sub ShowNotice(ByVal E As Connections.GenericEventArgs)
    Dim Frame As Frame
    Dim PrevTopic As String
    Dim tp As TabItem
    Dim ConsoleCreated As Boolean
    Dim cPage As ConsolePage
    Dim SelectedTab As TabItem
    Dim FindVar As Client.Channel.ChannelItem
    Friend Const CtcpQuote As Char = Chr(1)
    Dim SelectedBrowser, ChanObj, CVPage As Object
    Dim MCChanCen As ChanCenter
    Dim msgarchItem As Integer
#Region " Properties"
    Public Property ChannelObject() As ChatEngine.Client.Channel.IRCChannel
        Get
            Return CType(ChanObj, ChatEngine.Client.Channel.IRCChannel)
        End Get
        Set(ByVal value As ChatEngine.Client.Channel.IRCChannel)
            ChanObj = value
        End Set
    End Property
    Public WriteOnly Property WindowTitle() As String
        Set(ByVal value As String)
            Me.Text = value
        End Set
    End Property
    Public Shared Property ChatEngineInst() As ChatEngine.Client.IRCClient
        Get
            Return CEIVar
        End Get
        Set(ByVal value As ChatEngine.Client.IRCClient)
            CEIVar = value
        End Set
    End Property
#End Region
#Region " Buttons"
    Private Sub Close_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Input.MouseButtonEventArgs) Handles CloseButton.MouseDown
        Dim ISC As New ImageSourceConverter
        CloseButton.Source = ISC.ConvertFrom("pack://application:,,,/Images/Close-pressed.png")
    End Sub
    Private Sub Close_MouseEnter(ByVal sender As Object, ByVal e As System.Windows.Input.MouseEventArgs) Handles CloseButton.MouseEnter
        Dim ISC As New ImageSourceConverter
        CloseButton.Source = ISC.ConvertFrom("pack://application:,,,/Images/close-hover.png")
    End Sub
    Private Sub Close_MouseLeave(ByVal sender As Object, ByVal e As System.Windows.Input.MouseEventArgs) Handles CloseButton.MouseLeave
        Dim ISC As New ImageSourceConverter
        CloseButton.Source = ISC.ConvertFrom("pack://application:,,,/Images/close.png")
    End Sub
    Private Sub Close_MouseUp(ByVal sender As Object, ByVal e As System.Windows.Input.MouseButtonEventArgs) Handles CloseButton.MouseUp
        Dim ISC As New ImageSourceConverter
        CloseButton.Source = ISC.ConvertFrom("pack://application:,,,/Images/close.png")
        ConsoleCreated = False
        GC.Collect()
        Me.Close()
    End Sub
    Private Sub Max_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Input.MouseButtonEventArgs) Handles Max.MouseDown
        Dim ISC As New ImageSourceConverter
        Max.Source = ISC.ConvertFrom("pack://application:,,,/Images/Maximize-pressed.png")
    End Sub
    Private Sub Max_MouseEnter(ByVal sender As Object, ByVal e As System.Windows.Input.MouseEventArgs) Handles Max.MouseEnter
        Dim ISC As New ImageSourceConverter
        Max.Source = ISC.ConvertFrom("pack://application:,,,/Images/Maximize-hover.png")
    End Sub
    Private Sub Max_MouseLeave(ByVal sender As Object, ByVal e As System.Windows.Input.MouseEventArgs) Handles Max.MouseLeave
        Dim ISC As New ImageSourceConverter
        Max.Source = ISC.ConvertFrom("pack://application:,,,/Images/Maximize.png")
    End Sub
    Private Sub Max_MouseUp(ByVal sender As Object, ByVal e As System.Windows.Input.MouseButtonEventArgs) Handles Max.MouseUp
        Dim ISC As New ImageSourceConverter
        Min.Source = ISC.ConvertFrom("pack://application:,,,/Images/Minimize.png")
        If Me.WindowState <> Windows.WindowState.Maximized Then
            Me.WindowState = Windows.WindowState.Maximized
        Else
            Me.WindowState = Windows.WindowState.Normal
        End If
    End Sub
    Private Sub Min_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Input.MouseButtonEventArgs) Handles Min.MouseDown
        Dim ISC As New ImageSourceConverter
        Min.Source = ISC.ConvertFrom("pack://application:,,,/Images/Minimize-pressed.png")
    End Sub
    Private Sub Min_MouseEnter(ByVal sender As Object, ByVal e As System.Windows.Input.MouseEventArgs) Handles Min.MouseEnter
        Dim ISC As New ImageSourceConverter
        Min.Source = ISC.ConvertFrom("pack://application:,,,/Images/Minimize-hover.png")
    End Sub
    Private Sub Min_MouseLeave(ByVal sender As Object, ByVal e As System.Windows.Input.MouseEventArgs) Handles Min.MouseLeave
        Dim ISC As New ImageSourceConverter
        Min.Source = ISC.ConvertFrom("pack://application:,,,/Images/Minimize.png")
    End Sub
    Private Sub Min_MouseUp(ByVal sender As Object, ByVal e As System.Windows.Input.MouseButtonEventArgs) Handles Min.MouseUp
        Dim ISC As New ImageSourceConverter
        Min.Source = ISC.ConvertFrom("pack://application:,,,/Images/Minimize.png")
        Me.WindowState = Windows.WindowState.Minimized
    End Sub
#End Region
#Region " Chat Tab Creation"
    Public Sub SetFrameContent(Optional ByVal IsConsoleTab As Boolean = False)
        Try
            If IsConsoleTab = True And ConsoleCreated = False Then
                CVPage = New ConsolePage
                cPage = CVPage
                ConsoleCreated = True
            End If
            If IsConsoleTab = False Or IsConsoleTab = Nothing Then
                CVPage = New ChatViewPage
            End If
            Frame.Content = CVPage
            Frame.Width = tp.Width
            Frame.Height = tp.Height
            SetCVPageSettings()
        Catch ex As Exception
            MsgBox(ex.ToString)
        End Try
    End Sub
    Public Sub AddTabToContainer()
        tp = New Wpf.Controls.TabItem
        tp.Style = DirectCast(Me.Resources("SimpleTabItem"), Style)
        ChatTabs.Items.Add(tp)
    End Sub
    Public Sub SetCVPageSettings()
        'CVPage.VerticalAlignment = Windows.VerticalAlignment.Stretch
        'CVPage.HorizontalAlignment = Windows.HorizontalAlignment.Stretch
        CVPage.Width = Frame.Width
        CVPage.Height = Frame.Height
        If TypeOf (CVPage) Is ChatViewPage Then CVPage.Channel = ChannelObject
    End Sub
    Public Sub SetTabContent(ByVal ChannelName As String, ByVal IsConsoleTab As Boolean)
        Try
            Frame = New Frame
            tp.Content = Frame
            tp.Header = ChannelName
            Dim FindVar As Client.Channel.ChannelItem = SharedVars.Channels.Find(ChannelName)
            If Not IsNothing(FindVar.ChanObj) Then FindVar.ChanObj.ChannelTab = tp
            If Not IsConsoleTab = Nothing Then
                SetFrameContent(IsConsoleTab)
            Else
                SetFrameContent()
            End If
            CName = ChannelName
        Catch ex As Exception
            MsgBox(ex.ToString)
        End Try
    End Sub
    Public Sub CreateTab(ByVal ChannelName As String, Optional ByVal IsConsoleTab As Boolean = False)
        If IsConsoleTab = True And ConsoleCreated = True Then Exit Sub
        [Global].Services.Get(Of ILogging).AddItem("CreateTab:  here ", MessageType.FeedEngine_FMSF)
        ' Exit Sub
        ChatTabs.Dispatcher.BeginInvoke(Windows.Threading.DispatcherPriority.Normal, New Nav(AddressOf AddTabToContainer))
        ChatTabs.Dispatcher.BeginInvoke(Windows.Threading.DispatcherPriority.Normal, New SetContentOfTab(AddressOf SetTabContent), ChannelName, IsConsoleTab)
        Dim FindVar As Client.Channel.ChannelItem = SharedVars.Channels.Find(ChannelName)
        If Not FindVar.Name = Nothing Then
            If Not FindVar.ChanObj.TabIsLoaded = True Then
                FindVar.ChanObj.TabIsLoaded = True
            End If
        End If
    End Sub
#End Region
#Region " Message Processing"
    Private Sub Message_GotFocus(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles Message.GotFocus
        Message.Text = ""
        Message.FontStyle = FontStyles.Normal
    End Sub
    Private Sub Message_LostFocus(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles Message.LostFocus
        Message.Text = "Enter message here, then press Enter to send it!"
        Message.FontStyle = FontStyles.Italic
    End Sub
    Private Function ProcessCommands(ByVal CmdVar As String(), Optional ByVal RawCommand As String = "") As Boolean
        Try
            Dim f, b, User As String
            Dim msgargs As ShowMessageArgs
            f = SelectedTab.Header
            Select Case CmdVar(0)
                'cmd:ns register password email
                Case "cmd:raw"
                    a = RawCommand.Replace("cmd:raw", "")
                    ChatEngineInst.RawCommand(a)
                Case "cmd:who"
                    a = RawCommand.Replace("cmd:who", "")
                    ChatEngineInst.RawCommand("WHO " & a)
                Case "cmd:ns"
                    Dim CmdParams As String() = {CmdVar(2), CmdVar(3)}
                    ChatEngineInst.WriteRawNSCommand(CmdVar(1), CmdParams)
                    Return True
                Case "cmd:cs"
                    Dim cscomparms As String = RawCommand.Replace("cmd:cs", "")
                    ChatEngineInst.RawCommand("PRIVMSG CHANSERV " & cscomparms)
                Case "cmd:kick"
                    Try
                        a = RawCommand.Replace("cmd:kick", "")
                        b = a.Replace(CmdVar(1), "")
                        ChatEngineInst.Kick(f, CmdVar(1), Trim(b))
                        Return True
                    Catch ex As Exception
                        ChatEngineInst.Kick(f, CmdVar(1), GetUser)
                        Return True
                    End Try
                Case "cmd:mode"
                    Try
                        ChatEngineInst.RawCommand("MODE " & f & " " & CmdVar(1) & " " & CmdVar(2))
                    Catch ex As Exception
                        ChatEngineInst.RawCommand("MODE " & f & " " & CmdVar(1) & " " & Nothing)
                    End Try
                Case "cmd:ban"
                    ' Message.Text = "This guy tried to ban " & CmdVar(1) & " but it failed because his client is too primative to support modes"
                    ' ChatEngineInst.SendMessage(CType(SelectedTab, TabItem).Header, Message.Text)
                    Return True
                Case "cmd:id"
                    ChatEngineInst.IDNick(CmdVar(1))
                    Return True
                Case "cmd:nick"
                    ChatEngineInst.ChangeNickname(CmdVar(1))
                    SharedVars.Nick = CmdVar(1)
                    ChangeNick(SharedVars.Nick, CmdVar(1))
                    Return True
                Case "cmd:topic"
                    'Full Command: cmd:topic #rstat1 topic containing spaces
                    Dim A As String
                    A = RawCommand.Replace("cmd:topic", "")
                    If A.Contains(f) Then
                        A.Replace(f, "")
                    End If
                    ChatEngineInst.SetTopic(f, Trim(A))
                    Return True
                Case "cmd:join"
                    ChatEngineInst.JoinChannel(CmdVar(1))
                Case "cmd:quit"
                    a = RawCommand.Replace("cmd:quit", "")
                    If CmdVar.Length > 1 Then
                        ChatEngineInst.Disconnect(a)
                        Me.Close()
                    Else
                        ChatEngineInst.Disconnect()
                        Me.Close()
                    End If
                Case "cmd:action"
                    User = SharedVars.Nick
                    b = Message.Text.Replace("cmd:action", "")
                    ChatEngineInst.SendMessage(CType(SelectedTab, TabItem).Header, CtcpQuote & "ACTION" & b & CtcpQuote)
                    msgargs = New ShowMessageArgs(CType(SelectedTab, TabItem).Header, b, ShowMessageArgs.MsgTypeEnum.Action, User)
                    Me.Dispatcher.BeginInvoke(Windows.Threading.DispatcherPriority.ApplicationIdle, New DisplayMessage(AddressOf ShowContentInPage), msgargs)
                    Return True
                Case "cmd:amsg"

                Case "cmd:part"
                    Try
                        ChatEngineInst.PartChannel(CmdVar(1))
                    Catch ex As Exception
                        ChatEngineInst.PartChannel(f)
                    End Try
                Case Else
                    Return False
            End Select
        Catch ex As Exception
            [Global].Services.Get(Of Interfaces.ILogging).AddItem("ProcessCommands: " & ex.ToString, MessageType.General)
            Return False
        End Try
    End Function
    Private Sub ChangeNickAllTabs(ByVal PrevNick As String, ByVal NewNick As String)
        Try
            Dim B As String
            Dim SMA As ShowMessageArgs
            For Each tItem As TabItem In ChatTabs.Items
                Dim Frame2 As Frame = CType(tItem.Content, Frame)
                If Not TypeOf Frame2.Content Is ConsolePage Then
                    a = tItem.Header
                    B = CType(SelectedTab, TabItem).Header
                    If CType(Frame2.Content, ChatViewPage).FindUser(PrevNick) = True Then
                        SMA = New ShowMessageArgs(a, PrevNick & " is now known as " & NewNick, ShowMessageArgs.MsgTypeEnum.NickChange, NewNick)
                        ShowContentInPage(SMA)
                    End If
                    CType(Frame2.Content, ChatViewPage).ChangeNick(PrevNick, NewNick)
                End If
            Next
        Catch ex As Exception
            [Global].Services.Get(Of ILogging).AddItem("ShowContentInPage: Show message here", MessageType.General)
        End Try
    End Sub
    Private Sub ChangeNick(ByVal PrevNick As String, ByVal NewNick As String) Implements IChannelWindow.ChangeNick
        Me.Dispatcher.BeginInvoke(Windows.Threading.DispatcherPriority.ApplicationIdle, New ChangeNickDelegate(AddressOf ChangeNickAllTabs), PrevNick, NewNick)
    End Sub
    Private Sub Message_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Input.KeyEventArgs) Handles Message.KeyDown
        Dim A, B, f, User As String
        Dim cmdProccessed As Boolean
        If Message.Text = "Not Connected" Then Exit Sub
        Dim msgargs As ShowMessageArgs
        If e.KeyboardDevice.Modifiers = Windows.Input.ModifierKeys.Control Then
            If e.Key = Windows.Input.Key.K Then
                Message.AppendText(CChar(ChrW(3)).ToString())
            End If
            If e.Key = Windows.Input.Key.B Then
                Message.AppendText(CoreFX.Controls.RichTextIRC.BoldChar)
            End If
        End If
        If e.Key = Windows.Input.Key.Enter Then
            User = SharedVars.Nick
            CType(SelectedBrowser, ChatViewPage).MessageArchive.Push(Message.Text)
            f = SelectedTab.Header
            Dim CmdVar As String() = Message.Text.Split(New Char() {" "})
            cmdProccessed = ProcessCommands(CmdVar, Message.Text)
            If Not cmdProccessed Then
                If Not Message.Text.Contains("cmd") Then
                    ChatEngineInst.SendMessage(f, Message.Text)
                    For Each tItem As TabItem In ChatTabs.Items
                        A = tItem.Header
                        B = CType(SelectedTab, TabItem).Header
                        If A = B Then
                            If A <> B Then tItem.Style = DirectCast(Me.Resources("SimpleTabNewMsg"), Style)
                            Dim Frame2 As Frame = CType(tItem.Content, Frame)
                            If User = "Topic" Then
                                A = Message.Text
                            Else
                                A = Message.Text
                            End If

                            msgargs = New ShowMessageArgs(B, A, ShowMessageArgs.MsgTypeEnum.NewChanMsg, User)
                            Me.Dispatcher.BeginInvoke(Windows.Threading.DispatcherPriority.ApplicationIdle, New DisplayMessage(AddressOf ShowContentInPage), msgargs)
                            Exit For
                        End If
                    Next
                    Message.Text = ""
                End If
            Else
                Message.Text = ""
            End If
        End If
    End Sub
    Private Sub Message_PreviewKeyDown(ByVal sender As Object, ByVal e As System.Windows.Input.KeyEventArgs) Handles Message.PreviewKeyDown
        If msgarchItem < 0 Then msgarchItem = 0
        If e.Key = Windows.Input.Key.Up Then
            If TypeOf SelectedBrowser Is ChatViewPage Then
                Dim SB = CType(SelectedBrowser, ChatViewPage)
                Dim B = CType(SelectedTab, TabItem).Header
                If SB.MessageArchive.Count <> 0 Then
                    If Not msgarchItem > SB.MessageArchive.Count Then
                        If msgarchItem <> 0 Then
                            a = SB.MessageArchive.ElementAt(msgarchItem - 1)
                        Else
                            a = SB.MessageArchive.ElementAt(msgarchItem)
                        End If
                        msgarchItem = msgarchItem + 1
                        Message.Text = a
                    End If
                End If
            End If
        ElseIf e.Key = Windows.Input.Key.Down Then
            msgarchItem -= 1
            If TypeOf SelectedBrowser Is ChatViewPage Then
                Dim SB = CType(SelectedBrowser, ChatViewPage)
                Dim B = CType(SelectedTab, TabItem).Header
                If SB.MessageArchive.Count <> 0 Then
                    If Not msgarchItem > SB.MessageArchive.Count And Not msgarchItem < 0 Then
                        If msgarchItem <> 0 Then
                            a = SB.MessageArchive.ElementAt(msgarchItem - 1)
                        Else
                            a = SB.MessageArchive.ElementAt(msgarchItem)
                        End If
                        Message.Text = a
                    End If
                End If
            End If
        End If
    End Sub
#End Region
#Region " Others, Helper Functions"
    Private Sub RenderConMsgOnThread(ByVal Info As String)
        cPage.RenderMessage(Info)
    End Sub
    Private Sub NewConsoleMsg(ByVal Info As String)
        If Not IsNothing(cPage) Then
            Me.Dispatcher.BeginInvoke(Windows.Threading.DispatcherPriority.ApplicationIdle, New ClearUserList(AddressOf RenderConMsgOnThread), Info)
        Else
            'MsgBox(Info)
            [Global].Services.Get(Of Interfaces.ILogging).AddItem("NewConsoleMsg: " & Info, MessageType.General)
        End If
    End Sub
    Public Shared Sub InitQuery(ByVal User As String)
        ChatEngineInst.StartQuery(User)
    End Sub
    Private Sub ShowChannelCenter_Click(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles ShowChannelCenter.Click
        MCChanCen = New ChanCenter
        AddHandler MCChanCen.Loaded, AddressOf ChanCenLoad
        MCChanCen.ChatEngInst = ChatEngineInst
        MCChanCen.ChannelName = SelectedTab.Header.ToString
        MCChanCen.ShowDialog()
    End Sub
    Private Sub ChanCenLoad(ByVal sender As Object, ByVal e As System.EventArgs)
        ProcessCommands(New String() {"cmd:mode", "+b"})
    End Sub
    Private Sub NewUser(ByVal name As String, ByVal ChannelName As String)
        Dim A, B As String
        For Each tItem As TabItem In ChatTabs.Items
            A = tItem.Header
            B = CType(SelectedTab, TabItem).Header
            If A = ChannelName Then
                Dim Frame2 As Frame = CType(tItem.Content, Frame)
                CType(Frame2.Content, ChatViewPage).AddSingleUser(name, ChannelName)
            End If
        Next
    End Sub
    Public Sub New()
        MyBase.New()
        Me.InitializeComponent()
        ChatTabs.AllowAddNew = False
    End Sub
    Private Sub ChangeUIMode()
        ConsoleCreated = False
        Message.FontStyle = FontStyles.Italic
        Me.Message.Text = "Not Connected"
        Me.Message.IsEnabled = False
        Me.Tblabel.Text = "(Not Connected)"
        Me.Tblabel.FontStyle = FontStyles.Italic
    End Sub
    Public Sub HandleDisconnect()
        Me.Dispatcher.BeginInvoke(Windows.Threading.DispatcherPriority.Normal, New Nav(AddressOf ChangeUIMode))
    End Sub
    Public Sub ChangeTitle()
        Tblabel.Text = CName & " - " & Topic
        Tblabel.ToolTip = CName & " - " & Topic
        Me.Title = CName
    End Sub
    Private Sub Titlebar_MouseLeftButtonDown(ByVal sender As Object, ByVal e As System.Windows.Input.MouseButtonEventArgs) Handles Titlebar.MouseLeftButtonDown
        Me.DragMove()
    End Sub
    Public Function GetUser() As String
        Dim UVar As String = SharedVars.Nick
        Return UVar
    End Function
    Private Sub RenderANotice(ByVal e As Connections.GenericEventArgs)
        Dim Frame2 As Frame = CType(SelectedTab.Content, Frame)
        If TypeOf Frame2.Content Is ChatViewPage Then
            If CType(Frame2.Content, ChatViewPage).FindUser(e.User) = True Then
                Dim channame As String = CType(SelectedTab.Header, String)
                Dim SMA As ShowMessageArgs = New ShowMessageArgs(channame, e.Message, ShowMessageArgs.MsgTypeEnum.Notice, e.User)
                ShowContentInPage(SMA)
            End If
        End If
    End Sub
    Public Sub ShowContentInPage(ByVal E As ShowMessageArgs)
        Try
            [Global].Services.Get(Of ILogging).AddItem("ShowContentInPage: Showing message from " & E.User, MessageType.FeedSync_Queue)
            Dim Frame2 As Frame
            Dim Time = Format(System.DateTime.Now, "hh:mm")
            Dim FindVar As Client.Channel.ChannelItem = SharedVars.Channels.Find(E.ChannelName)
            If Not IsNothing(FindVar.ChanObj) Then
                If FindVar.ChanObj.TabIsLoaded = True Then
                    Dim A As String = ""
                    Dim UVar As String = SharedVars.Nick
                    Dim B As String = ""
                    For Each tItem As TabItem In ChatTabs.Items
                        A = tItem.Header
                        If Not IsNothing(SelectedTab) Then B = CType(SelectedTab, TabItem).Header
                        Frame2 = CType(tItem.Content, Frame)
                        If E.ChannelName = "Any" Then
                            If E.User = "ChanServ" Then
                                A = E.Message
                                CType(Frame2.Content, ChatViewPage).RenderQuit(E.Message)
                            End If
                        End If
                        '  If TypeOf Frame2.Content Is ChatViewPage Then
                        If LCase(A) = E.ChannelName Or UCase(A) = E.ChannelName Or A = E.ChannelName Then
                            If B <> A Then tItem.Style = DirectCast(Me.Resources("SimpleTabNewMsg"), Style)
                            ' Frame2 = CType(tItem.Content, Frame)
                            Select Case E.MessageType
                                Case ShowMessageArgs.MsgTypeEnum.Notice
                                    A = "--" & E.User & "-- " & E.Message
                                    CType(Frame2.Content, ChatViewPage).RenderNotice(A)
                                Case ShowMessageArgs.MsgTypeEnum.Disconnect
                                    A = "[" & Time & "] " & "* Disconnected"
                                    CType(Frame2.Content, ChatViewPage).RenderChannelMsg(A)
                                Case ShowMessageArgs.MsgTypeEnum.Action
                                    LogMessage(E.Message, E.ChannelName, E.User)
                                    Dim messvar = E.Message.Replace(CtcpQuote, "")
                                    A = "[" & Time & "] " & "* " & E.User & messvar
                                    CType(Frame2.Content, ChatViewPage).RenderChannelMsg(A)
                                Case ShowMessageArgs.MsgTypeEnum.ModeChange
                                    LogMessage(E.Message, E.ChannelName, E.User)
                                    A = "[" & Time & "] " & E.Message
                                    CType(Frame2.Content, ChatViewPage).RenderChannelMsg(A)
                                Case ShowMessageArgs.MsgTypeEnum.TopicChange
                                    LogMessage(E.Message, E.ChannelName, E.User)
                                    A = "[" & Time & "] " & E.Message
                                    CType(Frame2.Content, ChatViewPage).RenderChannelMsg(A)
                                Case ShowMessageArgs.MsgTypeEnum.NickChange
                                    LogMessage(E.Message, E.ChannelName, E.User)
                                    A = "[" & Time & "] " & "<<<< " & E.Message & " >>>>"
                                    CType(Frame2.Content, ChatViewPage).RenderChannelMsg(A)
                                Case ShowMessageArgs.MsgTypeEnum.NewUser
                                    LogMessage(E.Message, E.ChannelName, E.User)
                                    A = "[" & Time & "] " & E.Message
                                    CType(Frame2.Content, ChatViewPage).RenderChannelMsg(A)
                                Case ShowMessageArgs.MsgTypeEnum.NewChanMsg
                                    LogMessage(E.Message, E.ChannelName, E.User)
                                    A = "[" & Time & "] " & "<" & E.User & "> " & E.Message
                                    CType(Frame2.Content, ChatViewPage).BrowserDocumentText = A
                                Case ShowMessageArgs.MsgTypeEnum.Kicked
                                    LogMessage(E.Message, E.ChannelName, E.User)
                                    If UVar = E.User Then
                                        CType(Frame2.Content, ChatViewPage).RenderKicked(E.Message)
                                    Else
                                        CType(Frame2.Content, ChatViewPage).RenderChannelMsg(E.Message)
                                    End If
                            End Select
                        End If
                        ' End If
                    Next
                Else
                    [Global].Services.Get(Of ILogging).AddItem("ShowContentInPage: add item to queue here ", MessageType.General)
                End If
            End If
        Catch ex As Exception
            [Global].Services.Get(Of ILogging).AddItem("ShowContentInPage: " & ex.ToString, MessageType.General)
        End Try
    End Sub
    Private Sub ClearNicks(ByVal ChannelName As String)
        Dim A, B As String
        For Each tItem As TabItem In ChatTabs.Items
            A = tItem.Header
            If Not IsNothing(SelectedTab) Then B = CType(SelectedTab, TabItem).Header
            If A = ChannelName Then
                Dim Frame2 As Frame = CType(tItem.Content, Frame)
                CType(Frame2.Content, ChatViewPage).ClearUserList()
            End If
        Next
    End Sub
    Private Sub CTabButton_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)
        Dim I As Integer = ChatTabs.Items.IndexOf(SelectedTab)
        Dim A As String = SelectedTab.Header
        If A.Contains("#") Then ChatEngineInst.PartChannel(A)
        'ClearNicks(A)
        Dim FindVar As ChannelItem = SharedVars.Channels.Find(A)
        ChannelObject.Dispose(ChatEngineInst)
        If Not IsNothing(FindVar.ChanObj) Then
            SharedVars.Channels.Remove(FindVar)
        End If
        ChatTabs.Items.RemoveAt(I)
        FindVar = SharedVars.Channels.Find(A)
        If FindVar.ChanObj IsNot Nothing Then [Global].Services.Get(Of Interfaces.ILogging).AddItem("CTabButton_Click: ChanVar not NULL", MessageType.General)
        If I <> 0 Then ChatTabs.SelectedIndex = I - 1
        GC.Collect()
    End Sub
    Function MsgRender(ByVal Message As String, ByVal ChannelName As String, ByVal User As String) As String Implements ChatEngine.Client.IChannelWindow.RenderMessage
        Return Nothing
    End Function
    Public Sub LogMessage(ByVal Message As String, ByVal ChannelName As String, ByVal User As String)
        Try
            If IO.Directory.Exists(API.AppDataFolder.GetDataPath() & "Logs\") = False Then
                IO.Directory.CreateDirectory(API.AppDataFolder.GetDataPath() & "Logs\")
            End If
            If IO.Directory.Exists(API.AppDataFolder.GetDataPath() & "Logs\" & ChannelName) = False Then
                IO.Directory.CreateDirectory(API.GetDataPath() & "Logs\" & ChannelName)
            End If
            Dim DataPath As String = API.GetDataPath() & "Logs\" & ChannelName & "\" & System.DateTime.Now.Month & System.DateTime.Now.Day & System.DateTime.Now.Year & ".txt"
            If IO.File.Exists(DataPath) Then
                FileOpen(1, DataPath, OpenMode.Append)
            Else
                FileOpen(1, DataPath, OpenMode.Output)
            End If
            WriteLine(1, "[" & System.DateTime.Now.Hour & ":" & System.DateTime.Now.Minute & "]" & "<" & User & ">" & Message)
            FileClose(1)
        Catch ex As Exception
            [Global].Services.Get(Of Interfaces.ILogging).AddItem("RenderMessage: " & ex.ToString, MessageType.General)
        End Try
    End Sub
    Private Sub ChatTabs_SelectionChanged(ByVal sender As Object, ByVal e As System.Windows.Controls.SelectionChangedEventArgs) Handles ChatTabs.SelectionChanged
        SelectedTab = ChatTabs.SelectedItem
        If Not IsNothing(ChatTabs.SelectedItem) Then
            Dim Frame2 As Frame = CType(SelectedTab.Content, Frame)
            If TypeOf (Frame2.Content) Is ChatViewPage Then
                SelectedBrowser = Frame2.Content
                If Not IsNothing(Frame2.Content) Then Tblabel.Text = SelectedTab.Header.ToString & " - " & CType(Frame2.Content, ChatViewPage).ReturnUserCount() & " Users in channel"
                If CType(ChatTabs.SelectedItem, TabItem).Style Is DirectCast(Me.Resources("SimpleTabNewMsg"), Style) Then
                    CType(ChatTabs.SelectedItem, TabItem).Style = DirectCast(Me.Resources("SimpleTabItem"), Style)
                End If
            End If
        End If
        GC.Collect()
    End Sub
    Private Sub LoadUsers(ByVal E As Connections.NickListRecvArgs)
        Try
            Dim A, B As String
            [Global].Services.Get(Of Interfaces.ILogging).AddItem("LoadUsers: Loading nick list", MessageType.NetworkLayer)
            For Each tItem As TabItem In ChatTabs.Items
                A = tItem.Header
                If Not IsNothing(SelectedTab) Then B = CType(SelectedTab, TabItem).Header
                If A = E.ChanneName Then
                    Dim Frame2 As Frame = CType(tItem.Content, Frame)
                    If TypeOf Frame2.Content Is ChatViewPage Then
                        CType(Frame2.Content, ChatViewPage).LoadUserList(E)
                    End If
                End If
            Next
        Catch ex As Exception
            'SharedVars.Services.Get(Of ILogging).AddItem("LoadUsers: " & ex.ToString, MessageType.General)
            MsgBox(ex.ToString)
        End Try
    End Sub
    Public Sub ShowQuitMsg(ByVal User As String, ByVal Message As String)
        Dim B As Object
        For Each tItem As TabItem In ChatTabs.Items
            a = tItem.Header
            If Not IsNothing(SelectedTab) Then B = CType(SelectedTab, TabItem).Header
            Dim Frame2 As Frame = CType(tItem.Content, Frame)
            If TypeOf Frame2.Content Is ChatViewPage Then
                If CType(Frame2.Content, ChatViewPage).FindUser(User) = True Then
                    CType(Frame2.Content, ChatViewPage).RenderQuit("<<<< " & User & " has quit IRC, stating: " & Message & ">>>>")
                    CType(Frame2.Content, ChatViewPage).RemoveUserFromList(User)
                End If
            End If
        Next
    End Sub
    Private Sub Window1_Closed(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Closed
        ' ChatEngineInst.Disconnect()
    End Sub
    Private Sub RemoveUserFromChannel(ByVal User As String, ByVal Channel As String)
        Dim B As Object
        For Each tItem As TabItem In ChatTabs.Items
            a = tItem.Header
            If Not IsNothing(SelectedTab) Then B = CType(SelectedTab, TabItem).Header
            If a = Channel Then
                Dim Frame2 As Frame = CType(tItem.Content, Frame)
                CType(Frame2.Content, ChatViewPage).RemoveUserFromList(User)
                If User = GetUser() Then
                    ChatTabs.Items.Remove(tItem)
                End If
                Exit For
            End If
        Next
    End Sub
    Private Sub SetUserModePicFunc(ByVal E As Connections.UserModeArgs)
        Try
            Dim B As String
            Dim FindVar As ChannelItem = SharedVars.Channels.Find(E.Channel)
            If Not IsNothing(FindVar.ChanObj) Then
                If FindVar.ChanObj.TabIsLoaded = True Then
                    For Each tItem As TabItem In ChatTabs.Items
                        a = tItem.Header
                        If Not IsNothing(SelectedTab) Then B = CType(SelectedTab, TabItem).Header
                        If a = E.Channel Then
                            Dim Frame2 As Frame = CType(tItem.Content, Frame)
                            CType(Frame2.Content, ChatViewPage).ChangeUserPic(E.User, E.Mode, E.ModeAction, E.Channel)
                            Exit For
                        End If
                    Next
                Else
                    [Global].Services.Get(Of ILogging).AddItem("ShowContentInPage: add item to queue here ", MessageType.General)
                End If
            End If
            [Global].Services.Get(Of Interfaces.ILogging).AddItem("SetUserModePicFunc: Change User Mode", MessageType.FeedsList)
        Catch ex As Exception
            [Global].Services.Get(Of Interfaces.ILogging).AddItem("SetUserModePicFunc: " & ex.ToString, MessageType.FeedsList)
        End Try
    End Sub
    Private Sub Window1_Closing(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles Me.Closing
        a = MsgBox("This window is connected to a server. Are you sure you want to close it?", MsgBoxStyle.Question Or MsgBoxStyle.YesNo, "MChat")
        Select Case a
            Case vbYes
                ChatEngineInst.Disconnect()
                RaiseEvent Disconnected()
            Case Else
                e.Cancel = True
        End Select
    End Sub
    Private Sub Window1_Loaded(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles Me.Loaded
        [Global].Services.Get(Of Interfaces.ILogging).AddItem("Window1_Loaded: Window is loaded", MessageType.NetworkLayer)
        '   AddHandler CEIVar.AddLineToConsole, AddressOf NewConsoleMsg
    End Sub
#End Region
#Region " IChatWindow Procedures"
    Public Sub ChangeTopic(ByVal Topic As String, ByVal ChannelName As String) Implements ChatEngine.Client.IChannelWindow.ChangeTopic
        Try
            Dim TopicVar As String
            ChanName = ChannelName
            TopicVar = "Topic is: " & Topic
            Dim SMA As ShowMessageArgs = New ShowMessageArgs(ChannelName, TopicVar, ShowMessageArgs.MsgTypeEnum.TopicChange, "")
            Me.Dispatcher.BeginInvoke(Windows.Threading.DispatcherPriority.ApplicationIdle, New DisplayMessage(AddressOf ShowContentInPage), SMA)
        Catch ex As Exception
            [Global].Services.Get(Of ILogging).AddItem("ChangeTopic: " & ex.ToString, MessageType.UI)
        End Try
    End Sub
    Public Sub Kicked(ByVal E As Connections.KickedEventArgs) Implements ChatEngine.Client.IChannelWindow.Kicked
        Try
            Dim UVar As String
            UVar = GetUser()
            Dim MessageVar As String = "<<<< " & E.KickedUser & " was kicked from " & E.Channel & " by " & E.Kicker & " Reason: " & E.Reason & " >>>>"
            Dim SMA As ShowMessageArgs = New ShowMessageArgs(E.Channel, MessageVar, ShowMessageArgs.MsgTypeEnum.Kicked, E.KickedUser)
            Me.Dispatcher.BeginInvoke(Windows.Threading.DispatcherPriority.Normal, New DisplayMessage(AddressOf ShowContentInPage), SMA)
            Me.Dispatcher.BeginInvoke(Windows.Threading.DispatcherPriority.Normal, New AddNewUser(AddressOf RemoveUserFromChannel), E.KickedUser, New Object() {E.Channel})
            If UVar = E.KickedUser Then Me.Dispatcher.BeginInvoke(Windows.Threading.DispatcherPriority.Normal, New ClearUserList(AddressOf ClearNicks), E.Channel)
        Catch ex As Exception
            [Global].Services.Get(Of Interfaces.ILogging).AddItem("Kicked: " & ex.ToString, MessageType.General)
        End Try
    End Sub
    Public Sub NewMessage(ByVal User As String, ByVal Message As String, ByVal ChannelName As String) Implements ChatEngine.Client.IChannelWindow.NewMessage
        If ChannelName = "test" Then MsgBox("test")
        [Global].Services.Get(Of ILogging).AddItem("NewMessage: Sending message from " & User & "  to the channel window for rendering", MessageType.FeedSync_Queue)
        Dim messvar As String
        Dim msgtype As ShowMessageArgs.MsgTypeEnum
        If Message.Contains("ACTION") Then
            messvar = Message.Replace("ACTION", "")
            msgtype = ShowMessageArgs.MsgTypeEnum.Action
        Else
            messvar = Message
            msgtype = ShowMessageArgs.MsgTypeEnum.NewChanMsg
        End If
        Dim SMA As ShowMessageArgs = New ShowMessageArgs(LCase(ChannelName), Trim(messvar), msgtype, User)
        [Global].Services.Get(Of Interfaces.ILogging).AddItem("NewMessage: " & SMA.User & " " & SMA.Message & " " & SMA.ChannelName, MessageType.General)
        Me.Dispatcher.BeginInvoke(Windows.Threading.DispatcherPriority.Normal, New DisplayMessage(AddressOf ShowContentInPage), SMA)
    End Sub
    Public Sub UserJoined(ByVal User As String, ByVal ChannelName As String) Implements ChatEngine.Client.IChannelWindow.UserJoined
        Dim MessageVar As String = "<<<<< " & User & " has joined the channel >>>>>"
        Dim SMA As ShowMessageArgs = New ShowMessageArgs(ChannelName, MessageVar, ShowMessageArgs.MsgTypeEnum.NewUser, User)
        Me.Dispatcher.BeginInvoke(Windows.Threading.DispatcherPriority.Normal, New DisplayMessage(AddressOf ShowContentInPage), SMA)
        Me.Dispatcher.BeginInvoke(Windows.Threading.DispatcherPriority.Normal, New AddNewUser(AddressOf NewUser), User, New Object() {ChannelName})
    End Sub
    Public Sub NewQuery(ByVal User As String, ByVal FirstMsg As String, ByVal IsFirstMessage As Boolean) Implements ChatEngine.Client.IChannelWindow.NewQuery
    End Sub
    Public Sub PartFromChannel(ByVal User As String, ByVal Channel As String) Implements ChatEngine.Client.IChannelWindow.PartFromChannel
        If User = "" Then
            User = GetUser()
        End If
        Dim MessageVar As String = "<<<<< " & User & " has left the channel >>>>>"
        Dim SMA As ShowMessageArgs = New ShowMessageArgs(Channel, MessageVar, ShowMessageArgs.MsgTypeEnum.NewUser, User)
        Me.Dispatcher.BeginInvoke(Windows.Threading.DispatcherPriority.Normal, New DisplayMessage(AddressOf ShowContentInPage), SMA)
        Me.Dispatcher.BeginInvoke(Windows.Threading.DispatcherPriority.Normal, New AddNewUser(AddressOf RemoveUserFromChannel), User, New Object() {Channel})
    End Sub
    Public Sub ChangeUserMode(ByVal E As ChatEngine.Connections.UserModeArgs) Implements ChatEngine.Client.IChannelWindow.ChangeUserMode
        Dim MessageVar As String = ""
        Dim UserVar As String = ""
        If E.User = GetUser() Then
            UserVar = "You"
        Else
            UserVar = E.User
        End If
        Select Case E.Mode
            Case ModeEnum.Op
                If E.ModeAction = Connections.Action.Add Then
                    If UserVar = "You" Then
                        MessageVar = "<<<<< " & UserVar & " have been promoted to operator by " & E.Setter & ">>>>>"

                    Else
                        MessageVar = "<<<<< " & UserVar & " has been promoted to operator by " & E.Setter & ">>>>>"
                    End If
                Else
                    If UserVar = "You" Then
                        MessageVar = "<<<<< " & UserVar & " have been demoted from operator by " & E.Setter & ">>>>>"
                    Else
                        MessageVar = "<<<<< " & UserVar & " has been demoted from operator by " & E.Setter & ">>>>>"
                    End If
                End If
            Case ModeEnum.HalfOP
                If E.ModeAction = Connections.Action.Add Then
                    If UserVar = "You" Then
                        MessageVar = "<<<<< " & UserVar & " have been promoted to half-op by " & E.Setter & ">>>>>"
                    Else
                        MessageVar = "<<<<< " & UserVar & " has been promoted to half-op by " & E.Setter & ">>>>>"
                    End If
                Else
                    If UserVar = "You" Then

                    End If
                    MessageVar = "<<<<< " & UserVar & " has been demoted from half-op by " & E.Setter & ">>>>>"
                End If
            Case ModeEnum.User
                If E.ModeAction = Connections.Action.Add Then
                    If UserVar = "You" Then
                        MessageVar = "<<<<< " & UserVar & " have been given voice by " & E.Setter & ">>>>>"
                    Else
                        MessageVar = "<<<<< " & UserVar & " has been given voice by " & E.Setter & ">>>>>"
                    End If
                Else
                    If UserVar = "You" Then
                        MessageVar = "<<<<< " & UserVar & " have been devoiced by " & E.Setter & ">>>>>"
                    Else
                        MessageVar = "<<<<< " & UserVar & " has been devoiced by " & E.Setter & ">>>>>"
                    End If
                End If
            Case ModeEnum.Admin
                If E.ModeAction = Connections.Action.Add Then
                    If UserVar = "You" Then
                        MessageVar = "<<<<< " & UserVar & " have been promoted to channel admin by " & E.Setter & ">>>>>"
                    Else
                        MessageVar = "<<<<< " & UserVar & " has been promoted to channel admin by " & E.Setter & ">>>>>"
                    End If
                Else
                    If UserVar = "You" Then
                        MessageVar = "<<<<< " & UserVar & " have been demoted from channel admin by " & E.Setter & ">>>>>"
                    Else
                        MessageVar = "<<<<< " & UserVar & " has been demoted from channel admin by " & E.Setter & ">>>>>"
                    End If
                End If
            Case ModeEnum.Owner
                If UserVar = "You" Then
                    MessageVar = "<<<<< " & UserVar & " have been promoted to channel owner by " & E.Setter & ">>>>>"
                Else
                    MessageVar = "<<<<< " & UserVar & " has been promoted to channel owner by " & E.Setter & ">>>>>"
                End If

            Case ModeEnum.None
                MessageVar = "<<<<< " & UserVar & " has lost all channel privledges by " & E.Setter & ">>>>>"
        End Select
        Dim SMA As ShowMessageArgs = New ShowMessageArgs(E.Channel, MessageVar, ShowMessageArgs.MsgTypeEnum.ModeChange, UserVar)
        [Global].Services.Get(Of Interfaces.ILogging).AddItem("ChangeUserMode: " & E.Mode.ToString, MessageType.NetworkLayer)
        Me.Dispatcher.BeginInvoke(Windows.Threading.DispatcherPriority.ApplicationIdle, New DisplayMessage(AddressOf ShowContentInPage), SMA)
        Me.Dispatcher.BeginInvoke(Windows.Threading.DispatcherPriority.ApplicationIdle, New SetUserModePic(AddressOf SetUserModePicFunc), E)
    End Sub
    Public Sub LoadNickList(ByVal Channel As String, ByVal E As ChatEngine.Connections.NickListRecvArgs) Implements ChatEngine.Client.IChannelWindow.LoadNickList
        Me.Dispatcher.BeginInvoke(Windows.Threading.DispatcherPriority.ApplicationIdle, New LoadUserList(AddressOf LoadUsers), E)
    End Sub
    Public Sub ChannelModeChanged(ByVal E As ChatEngine.Connections.ChannelModeArgs) Implements ChatEngine.Client.IChannelWindow.ChannelModeChanged
        Dim Ax As String = E.Channel & " " & " " & E.UserModeCmbProp(0).User & " " & E.UserModeCmbProp(0).Mode.ToString
        [Global].Services.Get(Of Interfaces.ILogging).AddItem("ChannelModeChanged: " & Ax, MessageType.NetworkLayer)
    End Sub
    Public Sub UserQuit(ByVal User As String, ByVal Reason As String) Implements ChatEngine.Client.IChannelWindow.UserQuit
        Me.Dispatcher.BeginInvoke(Windows.Threading.DispatcherPriority.SystemIdle, New BroadcastMessage(AddressOf ShowQuitMsg), User, New Object() {Reason})
    End Sub
    Public Sub Disconnect() Implements ChatEngine.Client.IChannelWindow.Disconnect
        For Each tItem As TabItem In ChatTabs.Items
            Dim SMA As ShowMessageArgs = New ShowMessageArgs(tItem.Header, "", ShowMessageArgs.MsgTypeEnum.ModeChange, "")
            Me.Dispatcher.BeginInvoke(Windows.Threading.DispatcherPriority.ApplicationIdle, New DisplayMessage(AddressOf ShowContentInPage), SMA)
        Next
    End Sub
    Public Sub HandleNotice(ByVal E As ChatEngine.Connections.GenericEventArgs) Implements ChatEngine.Client.IChannelWindow.HandleNotice
        Me.Dispatcher.BeginInvoke(Windows.Threading.DispatcherPriority.ApplicationIdle, New ShowNotice(AddressOf RenderANotice), E)
    End Sub
#End Region
    Protected Overrides Sub Finalize()
        Me.ChatTabs = Nothing
        SharedVars.Channels.Clear()
        MyBase.Finalize()
    End Sub
End Class
Public Class ShowMessageArgs
    Dim CNameVar, MsgVar, UserVar As String
    Dim MsgTypeVar As MsgTypeEnum
    Public Enum MsgTypeEnum
        Action
        Notice
        Kicked
        NewUser
        NewChanMsg
        NickChange
        TopicChange
        ModeChange
        Disconnect
    End Enum
    Public Sub New(ByVal ChannelName1 As String, ByVal Message1 As String, ByVal MessageType1 As MsgTypeEnum, ByVal User1 As String)
        ChannelName = ChannelName1
        Message = Message1
        MessageType = MessageType1
        User = User1
    End Sub
    Public Property ChannelName() As String
        Get
            Return CNameVar
        End Get
        Set(ByVal value As String)
            CNameVar = value
        End Set
    End Property
    Public Property User() As String
        Get
            Return UserVar
        End Get
        Set(ByVal value As String)
            UserVar = value
        End Set
    End Property
    Public Property Message() As String
        Get
            Return MsgVar
        End Get
        Set(ByVal value As String)
            MsgVar = value
        End Set
    End Property
    Public Property MessageType() As MsgTypeEnum
        Get
            Return MsgTypeVar
        End Get
        Set(ByVal value As MsgTypeEnum)
            MsgTypeVar = value
        End Set
    End Property
End Class